<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.0.0">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="alternate" href="/atom.xml" title="el's blog" type="application/atom+xml">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css">


<script id="hexo-configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    version: '7.5.0',
    exturl: false,
    sidebar: {"position":"right","display":"post","offset":12,"onmobile":false},
    copycode: {"enable":false,"show_result":false,"style":null},
    back2top: {"enable":true,"sidebar":false,"scrollpercent":false},
    bookmark: {"enable":false,"color":"#222","save":"auto"},
    fancybox: false,
    mediumzoom: false,
    lazyload: false,
    pangu: false,
    algolia: {
      appID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    },
    localsearch: {"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},
    path: 'search.xml',
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    translation: {
      copy_button: '复制',
      copy_success: '复制成功',
      copy_failure: '复制失败'
    },
    sidebarPadding: 40
  };
</script>

  <meta name="description" content="我只知道 http 请求头有个 Connection 请求头设为 keep-alive 可以复用 tcp 连接，然而 http 请求 复用一 tcp 乎？">
<meta property="og:type" content="article">
<meta property="og:title" content="浏览器发送的 http 请求是复用一个 tcp 连接么">
<meta property="og:url" content="http:&#x2F;&#x2F;ever-lose.gitee.io&#x2F;2018&#x2F;07&#x2F;25&#x2F;tcp-http&#x2F;is-http-reuse-a-tcp&#x2F;index.html">
<meta property="og:site_name" content="el&#39;s blog">
<meta property="og:description" content="我只知道 http 请求头有个 Connection 请求头设为 keep-alive 可以复用 tcp 连接，然而 http 请求 复用一 tcp 乎？">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2019-11-08T06:19:30.969Z">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="http://ever-lose.gitee.io/2018/07/25/tcp-http/is-http-reuse-a-tcp/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome: false,
    isPost: true,
    isPage: false,
    isArchive: false
  };
</script>

  <title>浏览器发送的 http 请求是复用一个 tcp 连接么 | el's blog</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-meta">

    <div>
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">el's blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
        <h1 class="site-subtitle" itemprop="description">everlose's blog</h1>
      
  </div>

  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>
</div>


<nav class="site-nav">
  
  <ul id="menu" class="menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-fw fa-home"></i>首页</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-fw fa-th"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>归档</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>

</nav>
  <div class="site-search">
    <div class="popup search-popup">
    <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocorrect="off" autocapitalize="none"
           placeholder="搜索..." spellcheck="false"
           type="text" id="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result"></div>

</div>
<div class="search-pop-overlay"></div>

  </div>
</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content">
            

  <div class="posts-expand">
      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block " lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://ever-lose.gitee.io/2018/07/25/tcp-http/is-http-reuse-a-tcp/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.jpeg">
      <meta itemprop="name" content="everlose">
      <meta itemprop="description" content="focus on Js、CSS、Node...etc">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="el's blog">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          浏览器发送的 http 请求是复用一个 tcp 连接么
        </h2>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2018-07-25 00:00:00" itemprop="dateCreated datePublished" datetime="2018-07-25T00:00:00+08:00">2018-07-25</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2019-11-08 14:19:30" itemprop="dateModified" datetime="2019-11-08T14:19:30+08:00">2019-11-08</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/tcp-http/" itemprop="url" rel="index">
                    <span itemprop="name">tcp-http</span>
                  </a>
                </span>
            </span>

          
            <div class="post-description">我只知道 http 请求头有个 Connection 请求头设为 keep-alive 可以复用 tcp 连接，然而 http 请求 复用一 tcp 乎？</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h2 id="答案"><a href="#答案" class="headerlink" title="答案"></a>答案</h2><p>不一定。</p>
<p>如果发的不同域名，肯定不复用。</p>
<p>发的同域名。若第一个请求与第二个请求并行发送，不复用。</p>
<p>发的同域名，并且是第一个请求完事了才发第二个请求。则看是否有 connection: keep-alive 请求头，没有则不复用。</p>
<p>发的同域名，第一个请求完了后发第二个请求，有 connection: keep-alive 请求头。则复用同一个 TCP 连接。</p>
<h2 id="补充说明"><a href="#补充说明" class="headerlink" title="补充说明"></a>补充说明</h2><p>HTTP 1.1 里大概规范了几项提高性能的手段：</p>
<ol>
<li>持久连接 （keep-alive/persistent connection）</li>
<li>并行连接</li>
<li>Pipelining</li>
</ol>
<h3 id="持久连接"><a href="#持久连接" class="headerlink" title="持久连接"></a>持久连接</h3><p>每一个请求都会重新建立一个 TCP 连接，一旦响应返回，就关闭连接。 而建立一个连接，则需要进行三次握手。HTTP 1.1 出了一个请求头 connection，默认 keep-alive，告诉服务器不关闭 TCP 连接。</p>
<h3 id="并行连接"><a href="#并行连接" class="headerlink" title="并行连接"></a>并行连接</h3><p>由于现代网页通常包含了复数个（&gt;=10）资源，而按照默认设定，一个连接中的每一个请求必须等待收到响应后才能发送下一个请求，所以如果复数的资源请求全部在一个连接 one by one 发送给服务器显然会很慢，而为了弥补这一缺陷，浏览器通常会默认开启多个 TCP 连接，然后再根据每个连接的状态在其中依次发送数据请求，而且客户端有权任意关闭超发的连接。各个浏览器允许的并行连接数大致是这样的（From SO）：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">Firefox 2:  2</span><br><span class="line">Firefox 3+: 6</span><br><span class="line">Opera 9.26: 4</span><br><span class="line">Opera 12:   6</span><br><span class="line">Safari 3:   4</span><br><span class="line">Safari 5:   6</span><br><span class="line">IE 7:       2</span><br><span class="line">IE 8:       6</span><br><span class="line">IE 10:      8</span><br><span class="line">Chrome:     6</span><br></pre></td></tr></table></figure>

<p>由于 TCP 协议本身有慢启动的特征，会随着时间调谐连接的最大速度，因此在现代浏览器中持久连接和并行连接通常是搭配在一起使用的—— 一方面由于持久连接的存在，每个 TCP 连接已经处于调谐后的状态，另一方面持久连接可以避免重新三次握手的开销。</p>
<p>在 Chrome 中，页面初始并行加载一堆静态资源是会最大开 6 个 TCP 连接去并行运作，其后发 Ajax 请求则是复用之前的 TCP 连接。</p>
<h3 id="Pipelining"><a href="#Pipelining" class="headerlink" title="Pipelining"></a>Pipelining</h3><p>按照 HTTP 1.1 的描述，还有种可以提升性能的方案是管道化，可以在一个 TCP 连接中并行执行多个请求并返回。</p>
<p>因为这项技术比较复杂，如何能在一个 TCP 中有序的处理所接收到的包，并且不会乱序返回，这在早期没有规范，所以各大浏览器都没有支持此功能，形同鸡肋。</p>
<h2 id="关于-HTTP-2"><a href="#关于-HTTP-2" class="headerlink" title="关于 HTTP 2"></a>关于 HTTP 2</h2><p>HTTP 2 为了性能做了不少努力，比如提供了规范以支持连接的多路复用。</p>
<p>如前文所说，在同一个 TCP 连接里面同时发生两个请求响应就不是那么简单。而 HTTP 2 正是提供了这样的规范，可以给数据拆成包，并打上包的顺序标签以供 TCP 能正确认知接收的包的顺序。</p>
<p>所以很多网络优化的知识已经过时</p>
<ul>
<li>因为“所有的 HTTP 2.0 的请求都在一个 TCP 链接上”，“资源合并减少请求”，比如 CSS Sprites ,多个 JS 文件、CSS 文件合并等手段没有效果，或者说没有必要。</li>
<li>因为“多路复用”，采用“cdn1.cn,cdn2.cn,cdn3.cn，打开多个 TCP 会话，突破浏览器对同一域名的链接数的限制”的手段是没有必要的。因为因为资源都是并行交错发送，且没有限制，不需要额外的多域名并行下载。</li>
<li>内嵌资源（如base64的图片）的优化手段也变得没有意义了。而且使用服务器推送的资源的方式更加高效，因为客户端还可以缓存起来，甚至可以由不同的页面共享（依旧遵循同源策略）</li>
</ul>
<h2 id="参考"><a href="#参考" class="headerlink" title="参考"></a>参考</h2><ul>
<li><a href="https://linjunzhu.github.io/blog/2016/03/10/http2-zongjie/" target="_blank" rel="noopener">https://linjunzhu.github.io/blog/2016/03/10/http2-zongjie/</a></li>
<li><a href="https://www.zhihu.com/question/36469741" target="_blank" rel="noopener">https://www.zhihu.com/question/36469741</a></li>
</ul>

    </div>

    
    
    

      <footer class="post-footer">

        

          <div class="post-nav">
            <div class="post-nav-next post-nav-item">
                <a href="/2018/07/24/javascript/array-api/" rel="next" title="经典数组操作方法">
                  <i class="fa fa-chevron-left"></i> 经典数组操作方法
                </a>
            </div>

            <span class="post-nav-divider"></span>

            <div class="post-nav-prev post-nav-item">
                <a href="/2018/07/26/node/npm-installation-integrity-checksum-failure/" rel="prev" title="npm installation integrity checksum failure">
                  npm installation integrity checksum failure <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
      </footer>
    
  </article>
  
  
  

  </div>


          </div>
          
    <div class="comments" id="gitalk-container"></div>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#答案"><span class="nav-number">1.</span> <span class="nav-text">答案</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#补充说明"><span class="nav-number">2.</span> <span class="nav-text">补充说明</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#持久连接"><span class="nav-number">2.1.</span> <span class="nav-text">持久连接</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#并行连接"><span class="nav-number">2.2.</span> <span class="nav-text">并行连接</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Pipelining"><span class="nav-number">2.3.</span> <span class="nav-text">Pipelining</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#关于-HTTP-2"><span class="nav-number">3.</span> <span class="nav-text">关于 HTTP 2</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#参考"><span class="nav-number">4.</span> <span class="nav-text">参考</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <img class="site-author-image" itemprop="image" alt="everlose"
    src="/images/avatar.jpeg">
  <p class="site-author-name" itemprop="name">everlose</p>
  <div class="site-description" itemprop="description">focus on Js、CSS、Node...etc</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">97</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
        <span class="site-state-item-count">17</span>
        <span class="site-state-item-name">分类</span>
      </div>
      <div class="site-state-item site-state-tags">
        <span class="site-state-item-count">12</span>
        <span class="site-state-item-name">标签</span>
      </div>
  </nav>
</div>
  <div class="feed-link motion-element">
    <a href="/atom.xml" rel="alternate">
      <i class="fa fa-rss"></i>RSS
    </a>
  </div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/everlose" title="GitHub &amp;rarr; https:&#x2F;&#x2F;github.com&#x2F;everlose" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="/mailto:ever-lose@foxmail.com" title="E-Mail &amp;rarr; mailto:ever-lose@foxmail.com" rel="noopener" target="_blank"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
      </span>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">everlose</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> 强力驱动 v4.0.0
  </div>
  <span class="post-meta-divider">|</span>
  <div class="theme-info">主题 – <a href="https://mist.theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Mist</a> v7.5.0
  </div>

        












        
      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>
<script src="/js/utils.js"></script><script src="/js/motion.js"></script>
<script src="/js/schemes/muse.js"></script>
<script src="/js/next-boot.js"></script>



  




  <script src="/js/local-search.js"></script>













  

  

<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.css">

<script>
  NexT.utils.getScript('//cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.js', () => {
    var gitalk = new Gitalk({
      clientID: '48fe7d5cb2ac7e2c7fbf',
      clientSecret: '8f67b574218201d3b3ec6efe69276902e711e655',
      repo: 'everlose-blog',
      owner: 'everlose',
      admin: [''],
      id: '5fff7db8f9caa47ffc9c45a6038b9e3e',
        language: 'zh-CN',
      distractionFreeMode: 'true'
    });
    gitalk.render('gitalk-container');
  }, window.Gitalk);
</script>

</body>
</html>
